package com.yjd.comm.baseInfo.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.baseInfo.model.CityModel;
import com.yjd.comm.baseInfo.service.ICityService;
import com.yjd.comm.cache.up.ICacheUpdate;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServiceHolder;

/**
 * <b>description</b>：区域信息 <br>
 * <b>time</b>：2014-11-13下午8:59:55 <br>
 * <b>author</b>： ready likun_557@163.com
 */
@SuppressWarnings("unchecked")
public class CityUtil implements ICacheUpdate {

	private static Logger logger = Logger.getLogger(CityUtil.class);
	/**
	 * 禁止直接访问该map的值,通过getCitys()来访问
	 */
	private static List<CityModel> list;
	/**
	 * city的json数据
	 */
	private static String citysDataJson;
	private static final String SERVICE = "cityService";

	private static ICityService getCityService() {
		return ServiceHolder.getService(ICityService.class, SERVICE);
	}

	/**
	 * 获取字典所有数据
	 * 
	 * @return
	 * @throws Exception
	 */
	public static List<CityModel> getCitys() throws Exception {
		if (list == null) {
			synchronized (CityUtil.class) {
				if (list == null) {
					init();
				}
			}
		}
		return list;
	}

	/**
	 * 获取字典所有数据
	 * 
	 * @return
	 * @throws Exception
	 */
	public static List<CityModel> getProvinceCitys() throws Exception {
		List<CityModel> province=FrameUtil.newArrayList();
		for(CityModel c:getCitys()){
			if(c.getId()%1000==0){
				province.add(c);
			}
		}
		return province;
	}
	
	public static void FreshCache() throws Exception{
		init();
	}
	
	/**
	 * 此方法可以避免map在并发情况下，数据读取为空的情况
	 * 
	 * @throws Exception
	 */
	private static void init() throws Exception {
		synchronized (CityUtil.class) {
			List<CityModel> citys = getCityService().getModelList(null,DbWREnums.READ);
			Map<String, Map<String, Object>> jsonMap = new LinkedHashMap<String, Map<String, Object>>();
			for (CityModel cityModel : citys) {
				jsonMap.put(cityModel.getId().toString(), FrameUtil
						.newLinkedHashMap("id", cityModel.getId(), "name",
								cityModel.getName(), "parentid",
								cityModel.getParentid()));
			}
			citysDataJson = FrameUtil.json(jsonMap);
			list = citys;
		}
	}

	/**
	 * 根据cityid获取从跟节点一直到该节点的列表
	 * 
	 * @param cityid
	 * @return
	 * @throws Exception
	 */
	public static List<CityModel> getFullCitysById(Integer cityid)
			throws Exception {
		List<CityModel> result = new ArrayList<CityModel>();
		List<CityModel> temp = getCitys();
		Integer tempId = cityid;
		while (true) {
			boolean flag = true;
			for (CityModel cityModel : temp) {
				if (tempId.equals(cityModel.getId())) {
					result.add(0, cityModel);
					tempId = cityModel.getParentid();
					flag = false;
				}
			}
			if (flag) {
				break;
			}
		}
		return result;
	}

	/**
	 * 根据cityid获取该节点的所有子节点（依据子节点id排序）
	 * 
	 * @param cityid
	 * @return
	 * @throws Exception
	 */
	public static List<CityModel> getChildCitysById(Integer parentsId)
			throws Exception {
		List<CityModel> result = new ArrayList<CityModel>();
		List<CityModel> temp = getCitys();
		Integer tempId = parentsId;
		for (CityModel cityModel : temp) {
			if (tempId.equals(cityModel.getParentid())) {
				result.add(cityModel);
			}
		}
		Collections.sort(result, new Comparator<CityModel>(){
			@Override
			public int compare(CityModel o1, CityModel o2) {
				CityModel city1=o1;
				CityModel city2=o2;
				return city1.getId().compareTo(city2.getId());
			}});
		return result;
	}

	/**
	 * 获取从跟到cityid节点完整的id，之间用concat隔开
	 * 
	 * @param cityid
	 * @param concat
	 * @return
	 * @throws Exception
	 */
	public static String getFullCityIds(Integer cityid, String concat)
			throws Exception {
		List<CityModel> templist = getFullCitysById(cityid);
		if (templist != null) {
			List<Integer> cityids = new ArrayList<Integer>();
			for (CityModel cityModel : templist) {
				cityids.add(cityModel.getId());
			}
			return FrameUtil.arrayConcat(cityids, concat, false);
		}
		return null;
	}

	/**
	 * 获取从跟到cityid节点完整的name，之间用concat隔开
	 * 
	 * @param cityid
	 * @param concat
	 * @return
	 * @throws Exception
	 */
	public static String getFullCityNames(Integer cityid, String concat)
			throws Exception {
		if (cityid ==null){
			return null;
		}
		List<CityModel> templist = getFullCitysById(cityid);
		if (templist != null) {
			List<String> citynames = new ArrayList<String>();
			for (CityModel cityModel : templist) {
				citynames.add(cityModel.getName());
			}
			return FrameUtil.arrayConcat(citynames, concat, false);
		}
		return null;
	}
	
	/**
	 * 根据id获取city的信息
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static CityModel getCityModelById(Integer id) throws Exception {
		List<CityModel> temp = getCitys();
		for (CityModel cityModel : temp) {
			if (cityModel.getId().equals(id)) {
				return cityModel;
			}
		}
		return null;
	}

	/**
	 * 获取json数据
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getCitysDataJson() throws Exception {
		if (citysDataJson == null) {
			synchronized (CityUtil.class) {
				if (citysDataJson == null) {
					init();
				}
			}
		}
		return citysDataJson;
	}

	public void updateCache() {
		try {
			init();
			logger.info("更新区域字段缓存成功!");
		} catch (Exception e) {
			logger.error("更新区域缓存出错:" + e.getMessage(), e);
		}
	}

	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add(0, "222");
		list.add(0, "2221");
		System.out.println(list);
	}

}
